//
//  BleData.m
//  JC Health
//
//  Created by  on 2020/6/11.
//  Copyright © 2020 杨赛. All rights reserved.
//

#import "BleData.h"
#define SERVICE   @"FFF0"
#define SEND_CHAR @"FFF6"
#define REC_CHAR  @"FFF7"

@interface BleData ()
{
   
    
    
    

 
    
  
  
}
@end
@implementation BleData

+(BleData *)sharedManager
{
    static BleData * sharedAccountManagerInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedAccountManagerInstance = [[self alloc] init];
    });
    return sharedAccountManagerInstance;
}


-(void)setBleDelegate
{
    [NewBle sharedManager].delegate = self;
}


#pragma mark 设备正在被连接或者已经连接
-(BOOL)isBleConnectOrConnecting
{
    return [[NewBle sharedManager] isConnectOrConnecting];
}

#pragma mark 设备是否已经被连接
-(BOOL)isBleConnect
{
   return [[NewBle sharedManager] isActivityPeripheral];
}

#pragma mark 获取系统已经连接的设备
-(NSArray*)retrieveConnectedPeripherals
{
    NSArray * arrayConnectedPeripherals = [[NewBle sharedManager] retrieveConnectedPeripheralsWithServices:@[[CBUUID UUIDWithString:@"fff0"]]];
    return arrayConnectedPeripherals;
}

#pragma mark 设备扫描
-(void)startScanningWithServices:(nullable NSArray<CBUUID *> *)serviceUUIDs deviceBlock:(ScanDevice)scanDevice
{
    _scanDevice = scanDevice;
    [[NewBle sharedManager] startScanningWithServices:serviceUUIDs];
}

#pragma mark 设备连接
-(void)connectDevice:(CBPeripheral*)device
{
    [[NewBle sharedManager]  connectDevice:device];
}

-(NSArray*)retrieveConnectedPeripheralsWithStrIdentifier:(NSString*)strIdentifier
{    
    NSArray * bleArraty = [[NewBle sharedManager].CentralManage retrievePeripheralsWithIdentifiers:[NSArray arrayWithObject:[[NSUUID UUID] initWithUUIDString:strIdentifier]]];
    return bleArraty;
}

#pragma mark 断开连接
-(void)disConnectDevice
{
    [[NewBle sharedManager]  Disconnect];
}

#pragma mark 停止扫描
-(void)StopScan
{
    [[NewBle sharedManager].CentralManage stopScan];
}
-(CBManagerState)getBleStatus
{
    return [NewBle sharedManager].CentralManage.state;
}




#pragma mark  MyBleDelegate
-(void)ConnectSuccessfully
{
    _connectResult(YES,NULL);
}
-(void)Disconnect:(NSError *_Nullable)error
{
    
    !_disconnect?:_disconnect(error);
}
-(void)scanWithPeripheral:(CBPeripheral*_Nonnull)peripheral advertisementData:(NSDictionary<NSString *, id> *_Nonnull)advertisementData RSSI:(NSNumber *_Nonnull)RSSI
{
    _scanDevice(peripheral,advertisementData,RSSI);
}
-(void)ConnectFailedWithError:(nullable NSError *)error
{
    _connectResult(NO,error);
}
-(void)EnableCommunicate
{
    _communication(YES);
    

}


-(void)BleCommunicateWithPeripheral:(CBPeripheral*)Peripheral byte:(Byte *)byte dataLength:(NSInteger)dataLength
{


    

    NSDictionary * dicBleData;
    DATATYPE dataType;
    BOOL  isEnd = '\0';
    NSLog(@"cmd = %02X",byte[0]);
    switch (byte[0]) {
        case CMD_GET_VERSION:
        {
            NSString * strVersion = [NSString stringWithFormat:@"%x%x%x%x",byte[1],byte[2],byte[3],byte[4]];
            dicBleData = @{@"deviceVersion":strVersion};
            dataType = GetDeviceVersion;
            isEnd = YES;
        }
            break;
        case CMD_OTA_MODE:
        {
            dicBleData = nil;
            dataType = OTAMode;
            isEnd = YES;
        }
            break;
        default:
            NSLog(@"命令头 : %02x",byte[0]);
            dicBleData = nil;
            dataType = DataError;
            isEnd = YES;
            break;
    }
    _bleResult(dataType,dicBleData,isEnd);

}

#pragma mark  获取固件的版本号
-(void)getDeviceVersion
{
    char b[] = {CMD_GET_VERSION,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    NSData * bleData = [self SendData:b length:16 needCRC:YES];
    [self WriteDataToDevice:bleData device:[NewBle sharedManager].activityPeripheral];
}

-(void)enterOTAModeWithFileMD5:(NSString*)strFileMD5  signMD5:(NSData*)signMD5
{
    //18+64
    
   unsigned char b[82];
    b[0] = CMD_OTA_MODE;
    b[1] = 0;
    for (int i = 0; i<16; i++) {
       b[i+2] = (int)strtoul([[strFileMD5 substringWithRange:NSMakeRange(i*2, 2)] UTF8String], 0, 16);
      }
    Byte * bytes =  (Byte*)[signMD5 bytes];
    for (int i = 0;  i<signMD5.length; i++) {
        b[18+i] = bytes[i];
        NSLog(@" b[%d] = %02x", 18+i,b[18+i]);
    }
    NSData * bleData = [self SendData:b length:82 needCRC:NO];
    [self WriteDataToDevice:bleData device:[NewBle sharedManager].activityPeripheral];
}

-(NSString*)getDeviceName
{
    return [NewBle sharedManager].activityPeripheral.name;
}

-(NSString*)getDeviceIdentifier
{
    return [NewBle sharedManager].activityPeripheral.identifier.UUIDString;
}

-(CBCentralManager*)getCentralManager
{
    return [NewBle sharedManager].CentralManage;
}


#pragma mark  数据写入设备
-(void)WriteDataToDevice:(NSData*)data device:(CBPeripheral*)device
{
    [[NewBle sharedManager] writeValue:SERVICE characteristicUUID:SEND_CHAR p:device data:data];
}

- (NSData*)SendData:( unsigned char*)b length:(int)length needCRC:(BOOL)needCRC
{
    if(needCRC==YES){
        int sam = 0;
        for (int j = 0; j < length-1; j++)
        {
            sam += b[j];
        }
        b[length-1] = sam;
    }
    NSMutableData *data = [[NSMutableData alloc] initWithBytes:b length:length];
    return data;
    
}


@end

